<template>
    <div class="charts-content">
        <el-form :inline="true" :model="formData" class="demo-form-inline">
            <el-form-item label="账号" v-if="isAdmin">
                <el-select size="small" clearable v-model="formData.creatorName" placeholder="请选择账号" style="width: 150px" @change="getAccountStatistics">
                    <el-option
                        v-for="item in userList"
                        :key="item.id"
                        :label="item.username"
                        :value="item.username"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="分组">
                <el-select size="small" clearable v-model="formData.groups" placeholder="请选择分组" style="width: 150px" @change="handleChangeGroup">
                    <!-- <el-option label="设备" value="device" /> -->
                    <el-option label="国家" value="countryCode" />
                </el-select>
            </el-form-item>

            <el-form-item label="时间">
                <el-date-picker
                    size="small"
                    style="width: 355px"
                    @change="getAccountStatistics"
                    v-model="formData.times"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
            </el-form-item>
            <el-form-item>
                <el-radio-group v-model="formData.time" size="small" @change="getAccountStatistics">
                    <el-radio-button label="分钟" value="minute" />
                    <el-radio-button label="小时" value="hour" />
                    <el-radio-button label="天" value="day" />
                    <el-radio-button label="月" value="month" />
                </el-radio-group>
            </el-form-item>
        </el-form>
        <!-- :title="title" -->
         
        <LineAndPie
            ref="lineAndPie"
            v-if="!isNull"
            v-loading="loading"
            :width="'1200px'"
            :height="'200px'"
            :x-axis-data="dateList"
            :series-data="seriesData"
            :legend="['成功', '失败']"
            :legend-font-size="15"
            :colors="['#2d8cf0', '#ff5722']"
            @getMoreLastData="getMoreLastData"
        />
        <div v-else>
            <el-empty description="暂无数据"></el-empty>
        </div>
    </div>
  </template>
  
  <script setup>
  import LineAndPie from '@/components/charts/LineAndPie.vue'
  import { getStatistics } from '@/api/statistics/index.js'
  import { throttle } from '@/utils/index.js'

  
  const props = defineProps({
    app: {
        type: String,
        default: 'WA'
    },
    bundle: {
        type: String,
        default: ''
    },
    userList: {
        type: Array,
        default: () => []
    },
    isAdmin: {
        type: Boolean,
        default: false
    }
  })

  const now = new Date()
  // 前60分钟
  const lastMin = new Date(now.getTime() - 60 * 60 * 1000)
  // 前24小时
  const lastHour = new Date(now.getTime() - 24 * 60 * 60 * 1000)
  // 前30天
  const lastDay = new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000)
  // 前12个月
  const lastMonth = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000) 
  
  const timeMap = {
    minute: lastMin,
    hour: lastHour,
    day: lastDay,
    month: lastMonth,
  }

  const formData = ref({
    creatorName: '',
    times: [],
    time: 'day',
    groups: '',
  })

  const winStart = ref(lastDay)
  const getMoreLastData = throttle(() => {
    if (formData.value.times.length) {
        return
    }
    console.log("加载更多")
  }, 500)

  const lineAndPie = ref(null)
  const handleChangeGroup = (e) => {
    let values
    if(!e) {
        values = Object.keys(allSeries.value.all).map(item => {
            return {
                name: {
                    "fail": "失败",
                    "success": "成功",
                }[item],
                value: allSeries.value.all[item]
            }
        })
    } else {
        values = Object.keys(allSeries.value[e]).map(item => {
            return {
                name: item,
                value: allSeries.value[e][item].success
            }
        }).filter(item => item.name && item.name != "undefined")
    }

    setTimeout(() => {
        lineAndPie.value.changePieData(values)        
    })
  }

  const allSeries = ref({})
  const loading = ref(false)
  const dateList = ref({})
  const seriesData = ref([])
  const title = ref("")
  const isNull = ref(false)
  const getAccountStatistics = () => {
    const params = {
      model: 'account',
      chart: true,
      time: formData.value.time,
      groups: ['device', 'countryCode'],
    //   groups: formData.value.groups ? [formData.value.groups] : [],
      filters: {
        app: props.app,
      },
      times: void undefined,
    }

    if(formData.value?.filters?.creatorName) params.filters.creatorName = formData.value.creatorName
    if(formData.value?.times?.length) params.times = formData.value.times
    else params.times = [timeMap[formData.value.time], now]

    if(props.bundle) params.filters.bundle = props.bundle
    loading.value = true
    
    getStatistics(params).then(res => {
        if(res.xAxis.length === 0) {
            isNull.value = true
            return
        }
        isNull.value = false
        dateList.value = res.xAxis

        allSeries.value = res.series
        seriesData.value[0] = res.series.timeline.map(item => item.success)
        seriesData.value[1] = res.series.timeline.map(item => item.fail)

        title.value = props.app
        if(props.bundle) {
            title.value += {
                "net.whatsapp.WhatsApp": "个人版",
                "net.whatsapp.WhatsAppSMB": "商务版",
            }[props.bundle]
        }

        title.value += "账号统计"

        handleChangeGroup(null)
  
    }).catch(error => console.error('获取统计数据失败:', error)).finally(() => {
        loading.value = false
    })
  }
  
  onMounted(() => {
    getAccountStatistics()
  })
  
  </script>
  
  <style lang="scss" scoped>
  .charts-content{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  </style>
  